package cn.ldw.utils;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtTokenUtils {
    private static final String PRIVATE_KEY = "ldw123";  //私钥

    private static final String ISS = "ldw";  //签发人

    private static final long EXPIRATION_ONE_DAY = 604800l;  //签发时间

    public static String createToken(int userId) {
        //Jwt头
        Map<String,Object> header = new HashMap<>();
        header.put("typ","JWT");
        header.put("alg","HS256");
        //Jwt有效载荷部分
        Map<String, Object> claims = new HashMap<>();
        claims.put("user_id", userId);
        String token = Jwts.builder()
                .setIssuer(ISS)
                .setHeader(header)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_ONE_DAY * 1000))
                .signWith(SignatureAlgorithm.HS256, PRIVATE_KEY)
                .compact();
        return token;
    }

    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(PRIVATE_KEY).parse(token);
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
